//
//  RootViewController.m
//  kyMusicPlayer
//
//  Created by 翁科宇 on 2018/5/11.
//  Copyright © 2018年 翁科宇. All rights reserved.
//

#import "RootViewController.h"
#define playCrolViewWidth   _playControllerView.frame.size.width
#define playCrolViewHeight  _playControllerView.frame.size.height
#import "DetailViewController.h"

@interface RootViewController ()
//@property(nonatomic, strong)MusicPlayerManager *musicPlayer;
//@property(nonatomic, strong)SongInfo *songInfo;
@property(nonatomic, strong)DetailViewController *detailVC;
@end

MusicPlayerManager *musicPlayer;
SongInfo *songInfo;
@implementation RootViewController
#pragma mark - 顶部标题数组lazyLoad
- (NSMutableArray *)currentChannelsArray{
    if (_currentChannelsArray == nil) {
        _currentChannelsArray = [NSMutableArray arrayWithObjects:@"新歌", @"热歌", @"经典", @"情歌", @"网络", @"影视", @"欧美",@"Bill", @"摇滚", @"爵士", @"流行", nil];
    }
    return _currentChannelsArray;
}


- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"Music";
    musicPlayer = MusicPlayerManager.sharedManager;
    songInfo = SongInfo.sharedManager;
    //设置Subviews
    [self setUpSubViews];
    //设置KVO
    [songInfo addObserver:self forKeyPath:@"playSongIndex" options:NSKeyValueObservingOptionOld | NSKeyValueObservingOptionNew context:nil];
    [songInfo addObserver:self forKeyPath:@"isDataRequestFinish" options:NSKeyValueObservingOptionOld | NSKeyValueObservingOptionNew context:nil];
    [musicPlayer addObserver:self forKeyPath:@"finishPlaySongIndex" options:NSKeyValueObservingOptionOld | NSKeyValueObservingOptionNew context:nil];
    //Notification
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(playSongSetting) name:@"repeatPlay" object:nil];
    
}

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [self playStateRecover];
}
#pragma mark - KVO
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSKeyValueChangeKey,id> *)change context:(void *)context{
    if ([keyPath isEqualToString:@"playSongIndex"]) {
        [self playSongSetting];
    }
    if ([keyPath isEqualToString:@"isDataRequestFinish"]) {
        if (songInfo.isDataRequestFinish == YES) {
            songInfo.isDataRequestFinish = NO;
            
        }
    }
    if ([keyPath isEqualToString:@"finishPlaySongIndex"]) {
        [self playSongSetting];
    }
}

#pragma mark - 状态恢复
- (void)playStateRecover{
    [_currentPlaySongImage startRotating];
    if (musicPlayer.play.rate == 1) {
        NSLog(@"播放!");
        [_playAndPauseButton setImage:[UIImage imageNamed:@"cm2_fm_btn_pause"] forState:UIControlStateNormal];
        [_playAndPauseButton setImage:[UIImage imageNamed:@"cm2_fm_btn_pause_prs"] forState:UIControlStateHighlighted];
        [_currentPlaySongImage resumeRotate];
    }
    else{
        NSLog(@"暂停!");
        [_playAndPauseButton setImage:[UIImage imageNamed:@"cm2_fm_btn_play"] forState:UIControlStateNormal];
        [_playAndPauseButton setImage:[UIImage imageNamed:@"cm2_fm_btn_play_prs"]   forState:UIControlStateHighlighted];
        [_currentPlaySongImage stopRotating];
    }
}

#pragma mark - 播放音乐调用
- (void)playSongSetting{
    if (_playerTimeObserver != nil) {
        [musicPlayer.play removeTimeObserver:_playerTimeObserver];
        _playerTimeObserver = nil;
        [musicPlayer.play.currentItem cancelPendingSeeks];
        [musicPlayer.play.currentItem.asset cancelLoading];
    }
    [_playAndPauseButton setImage:[UIImage imageNamed:@"cm2_fm_btn_pause"] forState:UIControlStateNormal];
    [_playAndPauseButton setImage:[UIImage imageNamed:@"cm2_fm_btn_pause_prs"]  forState:UIControlStateHighlighted];
    // 主页面底部控制界面信息设置
    _songNameLb.text = songInfo.title;
    _singerNameLb.text = songInfo.author;
    _currentPlaySongImage.image = songInfo.pic_small;
    [_currentPlaySongImage resumeRotate];
    
    //detailVC页面控制界面信息设置
    _detailVC.topView.songTitleLb.text = songInfo.title;
    _detailVC.topView.singerNameLb.text = [[@"- " stringByAppendingString:songInfo.author] stringByAppendingString:@" -"];
    [_detailVC.midView.midIconView setAlbumImage:songInfo.pic_big];
    [_detailVC.midView.midLrcView AnalysisLRC:songInfo.lrcString];
    
    //播放设置
    [musicPlayer setplayItem:songInfo.file_link];
    [musicPlayer setplay];
    [musicPlayer startplay];
    //歌词index 清零
    songInfo.lrcIndex = 0;
    //控制界面设置
    [_detailVC playStateRecover];
    //播放结束通知
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(finishedPlaying) name:AVPlayerItemDidPlayToEndTimeNotification object:musicPlayer.play.currentItem];
    //设置Observer更新播放进度
    __weak typeof(self) weakSelf = self;
    _playerTimeObserver = [musicPlayer.play addPeriodicTimeObserverForInterval:CMTimeMake(1.0, 1.0) queue:dispatch_get_main_queue() usingBlock:^(CMTime time) {
        CGFloat currentTime = CMTimeGetSeconds(time);
        NSLog(@"当前播放时间：%f",currentTime);
        CMTime total = musicPlayer.play.currentItem.duration;
        CGFloat totalTime = CMTimeGetSeconds(total);
        //当前播放时间
        weakSelf.detailVC.bottomView.currentTimeLb.text = [songInfo intToString:(NSInteger)currentTime];
        //总时间
        weakSelf.detailVC.bottomView.durationTimeLb.text = [songInfo intToString:(NSInteger)totalTime];
        weakSelf.songSlider.value = (float)(currentTime / totalTime);
        weakSelf.detailVC.bottomView.songSlider.value = (float)(currentTime / totalTime);

        //更新歌词
        if (songInfo.isLrcExistFlg == YES) {
            if (!weakSelf.detailVC.midView.midLrcView.isDragging) {
                if (songInfo.lrcIndex <= songInfo.mLrcDictinary.count - 1) {
                    if ((NSInteger)currentTime >= [songInfo stringToInt:songInfo.mTimeArray[songInfo.lrcIndex]]) {
                        weakSelf.detailVC.midView.midLrcView.currentRow = songInfo.lrcIndex;

                        dispatch_async(dispatch_get_main_queue(), ^{
                            NSIndexPath *indexPath = [NSIndexPath indexPathForRow:weakSelf.detailVC.midView.midLrcView.currentRow inSection:0];
                            [weakSelf.detailVC.midView.midLrcView.tableView scrollToRowAtIndexPath:indexPath atScrollPosition:UITableViewScrollPositionMiddle animated:YES];
                            //锁屏歌词
                        });
                        //刷新歌词列表
                        [weakSelf.detailVC.midView.midLrcView.tableView reloadData];

                        songInfo.lrcIndex = songInfo.lrcIndex + 1;
                    }else{
                        if (songInfo.lrcIndex != 0) {
                            if (((NSInteger)currentTime >= [songInfo stringToInt:songInfo.mTimeArray[songInfo.lrcIndex - 1]]) &&((NSInteger)currentTime < [songInfo stringToInt:songInfo.mTimeArray[songInfo.lrcIndex]])) {
                                weakSelf.detailVC.midView.midLrcView.currentRow = songInfo.lrcIndex - 1;
                                dispatch_async(dispatch_get_main_queue(), ^{
                                    NSIndexPath *indexPath = [NSIndexPath indexPathForRow:weakSelf.detailVC.midView.midLrcView.currentRow inSection:0];
                                    [weakSelf.detailVC.midView.midLrcView.tableView scrollToRowAtIndexPath:indexPath atScrollPosition:UITableViewScrollPositionMiddle animated:YES];
                                    //锁屏歌词
                                });
                                //刷新歌词列表
                                [weakSelf.detailVC.midView.midLrcView.tableView reloadData];

                            }
                        }
                    }
                }
            }
        }
    }];
}
#pragma mark - 歌曲播放结束操作
- (void)finishedPlaying{
     NSLog(@"本歌曲播放结束，准备播放下一首歌曲！");
    [self nextButtonAction];
}

//MARK:设置Subviews
- (void)setUpSubViews{
    [self setupTopScrollView];
    [self setUpChildController];
    [self setUpContentScrollView];
    
    //初始化detailVC
    _detailVC = [[DetailViewController alloc] init];
    
    //主页底部控制View
    _playControllerView = [[UIView alloc] initWithFrame:CGRectMake(0, self.view.frame.size.height * 0.92 - self.navigationController.navigationBar.frame.size.height, self.view.frame.size.width, self.view.frame.size.height * 0.08)];
    _playControllerView.backgroundColor = RGBA(0, 0, 0, 0.5);
    _playControllerView.userInteractionEnabled = YES;
    [self.view bringSubviewToFront:_playControllerView];
    [self.view addSubview:_playControllerView];
    [_playControllerView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.equalTo(self.view.mas_bottom);
        make.left.equalTo(self.view.mas_left);
        make.right.equalTo(self.view.mas_right);
        make.width.mas_equalTo(self.view.frame.size.width);
        make.height.mas_equalTo(self.view.frame.size.height*0.08);
    }];
    
    //专辑图片
    _currentPlaySongImage = [[RoImageView alloc] initWithFrame:CGRectMake(playCrolViewHeight * 0.1, - playCrolViewHeight * 0.2, playCrolViewHeight * 1.1, playCrolViewHeight * 1.1)];
    _currentPlaySongImage.image = [UIImage imageNamed:@"cm2_simple_defaut_album_image"];
    _currentPlaySongImage.clipsToBounds = YES;
    _currentPlaySongImage.layer.cornerRadius = _playControllerView.frame.size.height *0.55;
    [_playControllerView addSubview:_currentPlaySongImage];
    _currentPlaySongImage.userInteractionEnabled = YES;
    UITapGestureRecognizer *tag = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(jumpToDeitalVC)];
    [_currentPlaySongImage addGestureRecognizer:tag];
    
    
    //播放/暂停按钮
    _playAndPauseButton = [[UIButton alloc] initWithFrame:CGRectMake(playCrolViewWidth*0.75, playCrolViewHeight *0.25, playCrolViewHeight * 0.65, playCrolViewHeight * 0.65)];
    [_playAndPauseButton setImage:[UIImage imageNamed:@"cm2_fm_btn_pause"] forState:UIControlStateNormal];
    [_playAndPauseButton setImage:[UIImage imageNamed:@"cm2_fm_btn_pause_prs"] forState:UIControlStateHighlighted];
    [_playAndPauseButton addTarget:self action:@selector(playAndPauseButtonAction:) forControlEvents:UIControlEventTouchUpInside];
    [_playControllerView addSubview:_playAndPauseButton];
    
    //下一首按钮
    _nextSongButton = [[UIButton alloc] initWithFrame:CGRectMake(playCrolViewWidth *0.88, playCrolViewHeight *0.25, playCrolViewHeight *0.65, playCrolViewHeight *0.65)];
    [_nextSongButton setImage:[UIImage imageNamed:@"cm2_fm_btn_next"] forState:UIControlStateNormal];
    [_nextSongButton setImage:[UIImage imageNamed:@"cm2_fm_btn_next_prs"] forState:UIControlStateHighlighted];
    [_nextSongButton addTarget:self action:@selector(nextButtonAction) forControlEvents:UIControlEventTouchUpInside];
    [_playControllerView addSubview:_nextSongButton];
    
    //歌曲进度条
    _songSlider = [[UISlider alloc] initWithFrame:CGRectMake(playCrolViewHeight * 1.3, 0, playCrolViewWidth - playCrolViewHeight * 1.3, playCrolViewHeight * 0.3)];
    [_songSlider setThumbImage:[UIImage imageNamed:@"cm2_simple_knob_trough_prs"] forState:UIControlStateNormal];
    [_songSlider setThumbImage:[UIImage imageNamed:@"cm2_simple_live_color_1_prs"] forState:UIControlStateHighlighted];
    _songSlider.tintColor = [UIColor whiteColor];
    [_songSlider addTarget:self action:@selector(playbackSliderValueChanged) forControlEvents:UIControlEventValueChanged];
    [_songSlider addTarget:self action:@selector(playbackSliderValueChangedFinish) forControlEvents:UIControlEventTouchUpInside];
    [_playControllerView addSubview:_songSlider];
    
    //歌名label
    _songNameLb = [[UILabel alloc] initWithFrame:CGRectMake(playCrolViewHeight * 1.3, playCrolViewHeight * 0.3, playCrolViewWidth * 0.5, playCrolViewHeight * 0.3)];
    _songNameLb.text = @"Unkown";
    _songNameLb.textColor = [UIColor whiteColor];
    _songNameLb.font = [UIFont systemFontOfSize:16];
    [_playControllerView addSubview:_songNameLb];
    
    //歌手名label
    _singerNameLb = [[UILabel alloc] initWithFrame:CGRectMake(playCrolViewHeight * 1.3, playCrolViewHeight * 0.7, playCrolViewWidth * 0.5, playCrolViewHeight * 0.2)];
    _singerNameLb.text = @"Unkown";
    _singerNameLb.textColor = RGBA(255, 255, 255, 0.95);
    _singerNameLb.font = [UIFont systemFontOfSize:13.0];
    [_playControllerView addSubview:_singerNameLb];
    
    
    
}
#pragma mark - 点击专辑图片跳转到deitalVC
- (void)jumpToDeitalVC{
    [self presentViewController:_detailVC animated:YES completion:nil];
}

#pragma mark - 播放或暂停
- (void)playAndPauseButtonAction:(UIButton *)sender{
    NSLog(@"当前播放曲目:%@",songInfo.title);
    if (musicPlayer.play.rate == 0) {
        [_playAndPauseButton setImage:[UIImage imageNamed:@"cm2_fm_btn_pause"] forState:UIControlStateNormal];
        [_playAndPauseButton setImage:[UIImage imageNamed:@"cm2_fm_btn_pause_prs"] forState:UIControlStateHighlighted];
        [_currentPlaySongImage resumeRotate];
        [musicPlayer startplay];
    }else{
        [_playAndPauseButton setImage:[UIImage imageNamed:@"cm2_fm_btn_play"] forState:UIControlStateNormal];
        [_playAndPauseButton setImage:[UIImage imageNamed:@"cm2_fm_btn_play_prs"] forState:UIControlStateHighlighted];
        [_currentPlaySongImage stopRotating];
        [musicPlayer stopplay];
    }
    
}
#pragma mark - 下一曲
- (void)nextButtonAction{
    if (songInfo.playSongIndex < songInfo.mSongs.count - 1) {
        HotSongInfo *info = songInfo.mSongs[songInfo.playSongIndex + 1];
        NSLog(@"即将播放下一首歌曲: 《%@》",info.title);
        [songInfo setSongInfo:info];
        [songInfo getSelectedSong:info.song_id index:songInfo.playSongIndex + 1];
    }
    else{
        HotSongInfo *info = songInfo.mSongs[0];
        NSLog(@"即将播放下一首歌曲: 《%@》",info.title);
        [songInfo setSongInfo:info];
        [songInfo getSelectedSong:info.song_id index:0];
    }
}
#pragma mark - 进度条改变值时触发
- (void)playbackSliderValueChanged{
    // 更新播放时间
    [self updateTime];
    //如果当前是暂停状态，则自动播放
    if (musicPlayer.play.rate == 0) {
        [_playAndPauseButton setImage:[UIImage imageNamed:@"cm2_fm_btn_pause"] forState:UIControlStateNormal];
        [_playAndPauseButton setImage:[UIImage imageNamed:@"cm2_fm_btn_pause_prs"] forState:UIControlStateHighlighted];
        [_currentPlaySongImage resumeRotate];
        [musicPlayer startplay];
    }
}
- (void)playbackSliderValueChangedFinish{
    // 更新播放时间
    [self updateTime];
    //如果当前是暂停状态，则自动播放
    if (musicPlayer.play.rate == 0) {
        [_playAndPauseButton setImage:[UIImage imageNamed:@"cm2_fm_btn_pause"] forState:UIControlStateNormal];
        [_playAndPauseButton setImage:[UIImage imageNamed:@"cm2_fm_btn_pause_prs"] forState:UIControlStateHighlighted];
        [_currentPlaySongImage resumeRotate];
        [musicPlayer startplay];
    }
}

#pragma mark - 更新播放时间
- (void)updateTime{
    CMTime duration = musicPlayer.play.currentItem.asset.duration;
    Float64 completeTime = CMTimeGetSeconds(duration);
    Float64 currentTime = (Float64)(self.songSlider.value) * completeTime;
    CMTime targetTime = CMTimeMake((int64_t)currentTime, 1);
    [musicPlayer.play seekToTime:targetTime];
    
    NSInteger index = 0;
    for (NSString *indexStr in songInfo.mTimeArray) {
        if ((NSInteger)currentTime < [songInfo stringToInt:indexStr]) {
            songInfo.lrcIndex = index;
        }else{
            index = index + 1;
        }
    }
}
#pragma mark - 初始化子控制器
- (void)setUpChildController{
    for (NSInteger i = 0; i < self.currentChannelsArray.count; i++) {
        ContentTableController *vc = [[ContentTableController alloc] init];
        vc.channelTitle = self.currentChannelsArray[i];
        [self addChildViewController:vc];
    }
}

#pragma mark - 初始化顶部标题scrollView
- (void)setupTopScrollView{
    TopScrollView *topScrollView = [[TopScrollView alloc] initWithFrame:CGRectMake(0, 0, ScreenWith, 30)];
    topScrollView.channelNameArray = self.currentChannelsArray;
    self.topScrollView = topScrollView;
    topScrollView.delegate = self;
    [self.view addSubview:topScrollView];
}

#pragma mark - 初始化ContentScrollView
- (void)setUpContentScrollView{
    UIScrollView *contentScrollView = [[UIScrollView alloc] init];
    self.contentScrollView = contentScrollView;
    contentScrollView.frame = self.view.bounds;
    contentScrollView.contentSize = CGSizeMake(contentScrollView.frame.size.width * self.currentChannelsArray.count, 0);
    contentScrollView.pagingEnabled = YES;
    contentScrollView.delegate = self;
    [self.view insertSubview:contentScrollView atIndex:0];
    [self scrollViewDidEndScrollingAnimation:contentScrollView];
}

#pragma mark - scrollView滑动停止调用
- (void)scrollViewDidEndScrollingAnimation:(UIScrollView *)scrollView{
    if (scrollView == self.contentScrollView) {
        NSInteger index = scrollView.contentOffset.x / self.contentScrollView.frame.size.width;
        ContentTableController *vc = self.childViewControllers[index];
        vc.view.frame = CGRectMake(scrollView.contentOffset.x, 0, self.contentScrollView.frame.size.width, self.contentScrollView.frame.size.height);
        vc.tableView.contentInset = UIEdgeInsetsMake(self.topScrollView.scrollView.frame.size.height, 0, self.tabBarController.tabBar.frame.size.height, 0);
        [scrollView addSubview:vc.view];
        
        for (NSInteger i = 0; i < self.contentScrollView.subviews.count; i++) {
            NSInteger currentIndex = vc.tableView.frame.origin.x / self.contentScrollView.frame.size.width;
            if ([self.contentScrollView.subviews[i] isKindOfClass:[UITableView class]]) {
                UITableView *theTableView = self.contentScrollView.subviews[i];
                NSInteger theIndex = theTableView.frame.origin.x / self.contentScrollView.frame.size.width;
                NSInteger gap = theIndex - currentIndex;
                if (gap <= 2 && gap >= -2) {
                    continue;
                }else{
                    [theTableView removeFromSuperview];
                }
            }
        }
        
    }
}

#pragma mark --UIScrollViewDelegate-- 滑动的减速动画结束后会调用这个方法
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView{
    if (scrollView == self.contentScrollView) {
        [self scrollViewDidEndScrollingAnimation:scrollView];
        NSInteger index = scrollView.contentOffset.x / self.contentScrollView.frame.size.width;
        [self.topScrollView selectChannelButtonWithIndex:index];
    }
}
#pragma mark - TopScrollViewDelegate
- (void)chooseChannelWithIndex:(NSInteger)index{
    [self.contentScrollView setContentOffset:CGPointMake(self.contentScrollView.frame.size.width * index, 0) animated:YES];
}


- (void)dealloc{
    [musicPlayer.play removeTimeObserver:_playerTimeObserver];
    _playerTimeObserver = nil;
    
    [musicPlayer.play.currentItem cancelPendingSeeks];
    [musicPlayer.play.currentItem.asset cancelLoading];
}



- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


@end
